//
//  SCStatusDAL.swift
//  weibo
//
//  Created by 阿城 on 15/12/22.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

private let kMaxDBCacheDateTime: NSTimeInterval = 7 * 24 * 60 * 60

class SCStatusDAL: NSObject {
    
    class func clearDBCache() {
        print(__FUNCTION__)
        
        // 准备时间字符串
        let date = NSDate(timeIntervalSinceNow: -kMaxDBCacheDateTime)
        
        // 转换日期格式
        let df = NSDateFormatter()
        df.locale = NSLocale(localeIdentifier: "en")
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let dateStr = df.stringFromDate(date)
        
        // sql
        // 提示：如果要删除数据的 SQL，先写 `SELECT *`，确认无误之后，再替换成 `DELETE`
        let sql = "DELETE FROM T_Status WHERE createTime < ?;"
        
        // 执行sql
        FMDBManager.shareManager.queue.inTransaction { (db, rollback) -> Void in
            if !db.executeUpdate(sql, dateStr) {
                rollback.memory = true
            } else {
                print("删除了 \(db.changes()) 条数据")
            }
        }
    }

    /// 保存数据
    private class func saveData(statuses: [[String: AnyObject]]){
        
        guard let userId = SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.uid else{
            printLog("用户没登陆")
            return
        }
        
        var sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) \n"
        sql += "VALUES (?, ?, ?);"
        
        FMDBManager.shareManager.queue.inTransaction { (db, rollBack) -> Void in
            
            var faild :Bool = false
            
            for status in statuses{
                
                let data = try! NSJSONSerialization.dataWithJSONObject(status, options: [])
                let statusId = status["id"] as! NSNumber
                
                if !db.executeUpdate(sql, statusId, data, userId){
                    faild = true
                    break
                }
            }
            
            if faild {
                printLog("失败")
            }else{
                printLog("加入了\(statuses.count)条")
            }
        }
    }
    
    /// 查找数据
    private class func checkData(sinceId: Int64, maxId: Int64) -> [[String: AnyObject]]?{
        
        guard let userId = SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.uid else{
            printLog("用户没登陆")
            return nil
        }
        
        // 1. 准备 SQL
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId) \n"
        
        if sinceId > 0 {        // 下拉刷新
            sql += " AND statusId > \(sinceId) \n"
        } else if maxId > 0 {   // 上拉刷新
            sql += " AND statusId <= \(maxId) \n"
        }
        sql += "ORDER BY statusId DESC LIMIT 5;"
        
        guard let array = FMDBManager.shareManager.execRecordSet(sql) else {
            
            return nil
        }
        
        // 3. 遍历数组，将 `status` 转换成字典数组
        var arrayM = [[String: AnyObject]]()
        for dict in array {
            // 将 json 的 data 反序列化
            let jsonData = dict["status"] as! NSData
            
            let statusDict = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
            
            // 添加到数组
            arrayM.append((statusDict as! [String : AnyObject]))
        }
        
        return arrayM
    }

    /// 加载数据
    class func loadData(sinceId: Int64, maxId: Int64, finished: (result: [[String: AnyObject]]?)->()){
        
        if let status = checkData(sinceId, maxId: maxId) where status.count > 0 {
            finished(result: status)
            return
        }
        
        let urlStr = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let paras: [String: AnyObject] = [
            "access_token" : SCUserInfoViewModel.shareInfoViewModel.token!,
            "since_id" : "\(sinceId)",
            "max_id" : "\(maxId == 0 ? 0 :maxId)",
            "count" : 5
        ]
        //        printLog(paras)
        
        HTTPClient.shareManager.request(HTTPClientRequestType.GET, url: urlStr, paras: paras) { (data, error) -> Void in
            if error != nil {
                printLog(error)
                finished(result: nil)
                return
            }
            
            guard let statuses = data!["statuses"] as? [[String:AnyObject]] else{
                printLog("没数据")
                finished(result: nil)
                return
            }

            saveData(statuses)
            finished(result: statuses)
        }
    }
    
}
